import { resolve, join, extname } from "path";
import fs from "fs";
import viteCompression from "vite-plugin-compression";
import { visualizer } from "rollup-plugin-visualizer";

// 加载插件模块
const loadPluginModules = async () => {
  return new Promise(async success => {
    const modulesPath = resolve(__dirname, "plugins");
    const fileNames = fs.readdirSync(modulesPath);
    let modulesImprot = [];
    fileNames.forEach(async item => {
      const filePath = join(modulesPath, item);
      if (
        fs.statSync(filePath).isFile() &&
        [".js"].includes(extname(filePath))
      ) {
        modulesImprot.push(import(`./plugins/${item}`));
      }
    });

    const modules = await Promise.all(modulesImprot);
    success(modules);
  });
};

// 基本配置
const baseCfg = (viteEnv = {}) => {
  const { VITE_BASE_URL } = viteEnv;
  return {
    envDir: "vite-env",
    resolve: {
      alias: {
        "@": resolve("./src")
      },
      extensions: [".js", ".mjs", ".vue", ".json", ".less", ".css"]
    },
    // server config
    server: {
      host: "0.0.0.0", // 服务器主机名，如果允许外部访问，可设置为"0.0.0.0"
      port: 3301,
      open: false,
      cors: true,
      // https: false,
      // 代理跨域
      proxy: {
        "/api": {
          target: "http://39.102.128.14:9001",
          changeOrigin: true
        }
      }
    },
    // build configure
    build: {
      outDir: "dist",
      reportCompressedSize: false,
      // 规定触发警告的 chunk 大小
      chunkSizeWarningLimit: 500,
      minify: "terser", // esbuild 打包更快，但是不能去除 console.log，去除 console 使用 terser 模式
      rollupOptions: {
        output: {
          chunkFileNames: "js/[name]-[hash].js", // 引入文件名的名称
          entryFileNames: "js/[name]-[hash].js", // 包的入口文件名称
          assetFileNames: "[ext]/[name]-[hash].[ext]", // 资源文件像 字体，图片等
          manualChunks: {
            echarts: ["echarts"],
            vue: ["vue", "vue-router", "vue-i18n"]
          }
        },
        plugins: [visualizer()]
      }
    },
    plugins: [
      viteCompression({
        verbose: true, // 默认即可
        disable: false, //开启压缩(不禁用)，默认即可
        deleteOriginFile: false, //删除源文件
        algorithm: "gzip", //压缩算法
        ext: ".gz", //文件类型
        threshold: 300 // 对大于 1kb 的文件进行压缩
      })
    ]
  };
};

// 插件配置
const pluginCfg = async (viteEnv = {}) => {
  const modulesArr = [];
  const modules = await loadPluginModules();
  modules.forEach(item => {
    const funcs = Object.values(item);
    funcs.forEach(it => {
      modulesArr.push(it(viteEnv));
    });
  });
  return modulesArr;
};

export { baseCfg, pluginCfg };
